import { InfoCircleFilled } from '@ant-design/icons';
import { Button, Checkbox, Divider, message, Select, Slider, Switch, Input, Segmented } from 'antd';
import { useEffect, useMemo, useState } from 'react';

import { DatasetSearchModeMap } from '@/common';
import { t } from '@/locales/i18n';
import { useSystemStore } from '@/store/useSystemStore';
import { DatasetSearchModeEnum } from '@/types/dataset';

import FormLabel from '../MyBox/FormLabel';
import MyModal from '../MyModal';
import MyRadio from '../MyRadio';
import QuestionTip from '../tooltip/QuestionTip';

const { TextArea } = Input;

export type DatasetParamsProps = {
  searchMode: `${DatasetSearchModeEnum}`;
  limit?: number;
  similarity?: number;
  usingReRank?: boolean;
  datasetSearchUsingExtensionQuery?: boolean;
  datasetSearchExtensionModel?: string;
  datasetSearchExtensionBg?: string;
  maxTokens?: number; // limit max tokens
  datasetSearchUsingKnowledgeGraph?: boolean;
  datasetSearchUsingChunkFilter?: boolean;
};
enum SearchSettingTabEnum {
  searchMode = 'searchMode',
  limit = 'limit',
  queryExtension = 'queryExtension',
}

const DatasetParamsModal = ({
  searchMode = DatasetSearchModeEnum.embedding,
  limit,
  similarity,
  usingReRank,
  maxTokens = 3000,
  datasetSearchUsingExtensionQuery,
  datasetSearchExtensionModel,
  datasetSearchExtensionBg,
  datasetSearchUsingKnowledgeGraph,
  datasetSearchUsingChunkFilter,
  onClose,
  onSuccess,
}: DatasetParamsProps & { onClose: () => void; onSuccess: (e: DatasetParamsProps) => void }) => {
  const { reRankModelList, llmModelList } = useSystemStore();
  const [refresh, setRefresh] = useState(false);
  const [currentTabType, setCurrentTabType] = useState(SearchSettingTabEnum.searchMode);

  const chatModelSelectList = (() =>
    llmModelList
      .filter((model) => model.usedInQueryExtension)
      .map((item) => ({
        value: item.model,
        label: item.name,
      })))();

  const [data, setData] = useState<DatasetParamsProps>({
    limit,
    similarity,
    searchMode,
    usingReRank: !!usingReRank,
    datasetSearchUsingExtensionQuery,
    datasetSearchExtensionModel: datasetSearchExtensionModel || chatModelSelectList[0]?.value,
    datasetSearchExtensionBg,
    datasetSearchUsingKnowledgeGraph,
    datasetSearchUsingChunkFilter,
  });

  // const datasetSearchUsingCfrForm = watch('datasetSearchUsingExtensionQuery');
  // const queryExtensionModel = watch('datasetSearchExtensionModel');
  // const cfbBgDesc = watch('datasetSearchExtensionBg');
  // const usingReRankWatch = watch('usingReRank');
  // const searchModeWatch = watch('searchMode');

  const searchModeList = useMemo(() => {
    const list = Object.values(DatasetSearchModeMap);
    return list;
  }, []);

  const showSimilarity = useMemo(() => {
    if (similarity === undefined) return false;
    if (data.usingReRank) return true;
    if (data.searchMode === DatasetSearchModeEnum.embedding) return true;
    return false;
  }, [data.searchMode, similarity, data.usingReRank]);

  const showReRank = useMemo(() => {
    return usingReRank !== undefined && reRankModelList.length > 0;
  }, [reRankModelList.length, usingReRank]);

  useEffect(() => {
    if (data.datasetSearchUsingExtensionQuery) {
      !data.datasetSearchExtensionModel &&
        setData({
          ...data,
          datasetSearchExtensionModel: chatModelSelectList[0]?.value,
        });
    } else {
      setData({
        ...data,
        datasetSearchExtensionModel: '',
      });
    }
  }, [chatModelSelectList, data]);

  return (
    <MyModal
      isOpen
      onClose={onClose}
      iconSrc="menu_set"
      title={t('core.dataset.search.Dataset Search Params')}
      minW="600px"
    >
      <div className="flex-auto overflow-auto">
        <Segmented
          className="custom-segmented"
          block
          options={[
            {
              // icon: 'modal/setting',
              label: t('core.dataset.search.search mode'),
              value: SearchSettingTabEnum.searchMode,
            },
            {
              // icon: 'support/outlink/apikeyFill',
              label: t('core.dataset.search.Filter'),
              value: SearchSettingTabEnum.limit,
            },
            {
              label: t('core.module.template.Query extension'),
              value: SearchSettingTabEnum.queryExtension,
              // icon: '/imgs/workflow/cfr.svg',
            },
          ]}
          value={currentTabType}
          onChange={setCurrentTabType}
        />
        {currentTabType === SearchSettingTabEnum.searchMode && (
          <>
            <MyRadio
              className="mt-4 grid-cols-2"
              list={searchModeList}
              value={data.searchMode}
              onChange={(e) => {
                setData({
                  ...data,
                  searchMode: e as `${DatasetSearchModeEnum}`,
                });
                setRefresh(!refresh);
              }}
            />
            <>
              <Divider className="my-4" />

              <div
                className={`relative flex cursor-pointer select-none items-center rounded-2xl border border-gray-300 border-opacity-20 px-4 py-3 ${
                  data.usingReRank ? 'border-primary bg-primary-700' : ''
                }`}
                onClick={(e) => {
                  if (!showReRank) {
                    return message.warning(t('core.ai.Not deploy rerank model'));
                  }
                  setData({
                    ...data,
                    usingReRank: !data.usingReRank,
                  });
                  setRefresh((state) => !state);
                }}
              >
                <div className="flex items-center space-x-3">
                  <div
                    className={`flex h-8 w-8 items-center justify-center rounded-full ${
                      data.usingReRank ? 'bg-green-100' : 'bg-gray-200'
                    }`}
                  >
                    {data.usingReRank ? (
                      <svg
                        className="h-5 w-5 text-green-600"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
                        />
                      </svg>
                    ) : (
                      <svg
                        className="h-5 w-5 text-gray-400"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"
                        />
                      </svg>
                    )}
                  </div>
                  <div>
                    <div className="font-medium text-gray-700">
                      {t('core.dataset.search.ReRank')}
                    </div>
                    <div className="text-xs text-gray-600">
                      {t('core.dataset.search.ReRank desc')}
                    </div>
                  </div>
                </div>
                <div className="ml-auto">
                  <Checkbox checked={data.usingReRank} />
                </div>
              </div>
            </>
          </>
        )}
        {currentTabType === SearchSettingTabEnum.limit && (
          <div className="mt-4 flex flex-col p-4">
            {limit !== undefined && (
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div className="ml-2 flex items-center space-x-2">
                    <span className="font-medium text-gray-700">
                      {t('core.dataset.search.Max Tokens')}
                    </span>
                    <QuestionTip
                      className="ml-1"
                      title={t('core.dataset.search.Max Tokens Tips')}
                    />
                  </div>
                  <div className="rounded-full bg-blue-400 px-3 py-1 text-sm font-medium">
                    {data.limit}
                  </div>
                </div>
                <div className="px-2">
                  <Slider
                    min={100}
                    max={maxTokens}
                    step={50}
                    value={data.limit ?? 1000}
                    onChange={(val) => {
                      setData({
                        ...data,
                        limit: val,
                      });
                      setRefresh(!refresh);
                    }}
                    tooltip={undefined}
                  />
                </div>
                <div className="flex justify-between px-2 text-xs text-gray-600">
                  <span>100</span>
                  <span>{maxTokens}</span>
                </div>
              </div>
            )}
            <div className="mt-10 space-y-4">
              <div className="flex items-center justify-between">
                <div className="ml-2 flex items-center space-x-2">
                  <span className="font-medium text-gray-700">
                    {t('core.dataset.search.Min Similarity')}
                  </span>
                  <QuestionTip
                    className="ml-1"
                    title={t('core.dataset.search.Min Similarity Tips')}
                  />
                </div>
                {showSimilarity && (
                  <div className="text-green-800 rounded-full bg-green-100 px-3 py-1 text-sm font-medium">
                    {data.similarity ?? 0.5}
                  </div>
                )}
              </div>
              <div className="flex-1">
                {showSimilarity ? (
                  <div>
                    <div className="px-2">
                      <Slider
                        min={0}
                        max={1}
                        step={0.01}
                        value={data.similarity ?? 0.5}
                        onChange={(val) => {
                          setData({
                            ...data,
                            similarity: val,
                          });
                          setRefresh(!refresh);
                        }}
                      />
                    </div>
                    <div className="flex justify-between px-2 text-xs text-gray-600">
                      <span>0.0</span>
                      <span>1.0</span>
                    </div>
                  </div>
                ) : (
                  <div className="ml-2 text-gray-600">
                    {t('core.dataset.search.No support similarity')}
                  </div>
                )}
              </div>
            </div>
          </div>
        )}
        {currentTabType === SearchSettingTabEnum.queryExtension && (
          <div>
            {/* <div className="mt-2 text-xs text-gray-600">
              {t('core.dataset.Query extension intro')}
            </div> */}
            <div className="mt-4 flex flex-1 items-center gap-2 rounded-2xl border border-primary bg-primary-700 p-2">
              <InfoCircleFilled className="ml-2 mr-1" size={28} style={{ color: '#6640FF' }} />
              <div className="text-xs">{t('core.dataset.Query extension intro')}</div>
            </div>
            <div className="mt-3 flex items-center gap-2">
              <FormLabel>{t('core.dataset.search.Using query extension')}</FormLabel>
              {/* <Switch value={data.datasetSearchUsingExtensionQuery} {...register('datasetSearchUsingExtensionQuery')} /> */}
              <div className="ml-auto">
                <Switch
                  value={data.datasetSearchUsingExtensionQuery}
                  onChange={(e) => {
                    setData({
                      ...data,
                      datasetSearchUsingExtensionQuery: e,
                    });
                  }}
                />
              </div>
            </div>
            {data.datasetSearchUsingExtensionQuery === true && (
              <>
                <div className="mt-4 flex items-center gap-2">
                  <FormLabel>{t('core.ai.Model')}</FormLabel>
                  <div className="ml-auto flex">
                    <Select
                      className="w-full"
                      value={data.datasetSearchExtensionModel}
                      options={chatModelSelectList}
                      onChange={(e) => {
                        setData({
                          ...data,
                          datasetSearchExtensionModel: e,
                        });
                      }}
                    />
                  </div>
                </div>
                <div className="mt-3">
                  <div className="flex items-center">
                    <FormLabel>{t('core.app.edit.Query extension background prompt')}</FormLabel>
                    <QuestionTip
                      className="ml-1"
                      title={t('core.app.edit.Query extension background tip')}
                    />
                  </div>
                  <div className="mt-2">
                    <TextArea
                      className="h-auto"
                      rows={4}
                      value={data.datasetSearchExtensionBg}
                      onChange={(e) => {
                        setData({
                          ...data,
                          datasetSearchExtensionBg: e.target.value,
                        });
                      }}
                      placeholder={t('core.module.QueryExtension.placeholder')}
                    />
                  </div>
                </div>
              </>
            )}
          </div>
        )}
      </div>
      <div className="ml-auto mt-4 flex">
        <Button className="mr-3" onClick={onClose}>
          {t('common.Close')}
        </Button>
        <Button
          type="primary"
          onClick={() => {
            onClose();
            // handleSubmit(onSuccess)();
            onSuccess(data);
          }}
        >
          {t('common.Done')}
        </Button>
      </div>
    </MyModal>
  );
};

export default DatasetParamsModal;
